// let dispatch = store.dispatch;
// 中间件的核心原理就是重写dispatch 方法，在原始的dispatch方法之前和之后加入一些自定义的逻辑
// store.dispatch = function (action) {
//   console.log("prev state", store.getState());
//   dispatch(action);
//   console.log("next state", store.getState());

import compose from "./compose";

// };
function applyMiddleware(...middlewares) {
  return function (createStore) {
    return function (reducer, preloadedState) {
      let store = createStore(reducer, preloadedState); // 先创建一个仓库
      let dispatch;
      let middlewareAPI = {
        getState: store.getState,
        dispatch: (action) => dispatch(action),
      };
      // dispatch = logger(middlewareAPI)(store.dispatch);
      let chain = middlewares.map((middleware) => middleware(middlewareAPI));
      dispatch = compose(...chain)(store.dispatch);
      return {
        ...store,
        dispatch,
      };
    };
  };
}

export default applyMiddleware;
